import { ref } from 'vue'

/**
 * 倒计时 Hook
 * @param {number} duration 倒计时时间 (秒)，默认60
 * @param {boolean} autoStart 是否自动开始
 * @returns {object} { countDown, isRunning, start, stop, reset }
 */
export function useCountDown(duration = 60, autoStart = false) {
  const countDown = ref(duration)
  const isRunning = ref(false)
  let timer = null

  const start = () => {
    if (isRunning.value) { return }
    isRunning.value = true
    timer = setInterval(() => {
      if (countDown.value > 0) {
        countDown.value--
      }
      else {
        stop()
      }
    }, 1000)
  }

  const stop = () => {
    if (timer) {
      clearInterval(timer)
      timer = null
    }
    isRunning.value = false
  }

  const reset = (newDuration) => {
    stop()
    countDown.value = newDuration || duration
  }

  if (autoStart) {
    start()
  }

  return {
    countDown,
    isRunning,
    start,
    stop,
    reset,
  }
}
